import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw,
} from "vue-router";
import Login from "../views/Login.vue";
import Cookies from "js-cookie";
import { useMenusStroe } from "../stores/menus";
import { useUserInfoStore } from "../stores/userInfo";
import * as api from "../request/api";
const router = createRouter({
  history: createWebHashHistory(), // 路由模式是哈希模式
  routes: [
    {
      path: "/login",
      name: "login",
      component: Login,
    },
    {
      path: "/",
      name: "home",
      redirect: "/index",
      component: () => import("../views/Layout.vue"),
      children: [
        {
          path: "/index",
          name: "index",
          component: () => import("../views/HomeView.vue"),
          meta: {
            title: "首页",
          },
        }
      ],
    },
  ],
});

// 1. 没有登录的时候 ， 不能直接进入首页菜单列表 ，
// 2. 当登录之后 ，存在token , 是否需要重新获取菜单栏的数据
// 3. 假设有某个路由（商品分类）的权限，那么同时默认拥有其子路由(商品分类编辑)的路由权限
// 结论 ：需要做路由守卫

// 全局前置路由守卫
router.beforeEach(async (to, from, next) => {
  // console.log("to",to);
  // console.log("from",from);

  // 如果存在token ，并且没有菜单数据的时候，那么重新获取菜单栏数据
  const menusStore = useMenusStroe();
  const token = Cookies.get("token");
  const userinfoStore = useUserInfoStore();
  // console.log(userinfoStore);
  // console.log(token);
  // console.log(menusStore);

  if (token && userinfoStore.username === "") {
    // 重新请求
    // 获取用户信息,比如菜单栏,用户名
    try {
      let adminInfo = await api.admin.getAdminInfo();
      // 获取到菜单后,存到pinia
      menusStore.updatedMenus(adminInfo.menus);
      // 获取到用户名和角色,存到pinia中
      userinfoStore.updataUserInfo(adminInfo.username, adminInfo.roles)

      // 依赖菜单栏 来动态的生成路由表,addRotuer
      menusStore.sortedMenus.forEach((el) => {
        // console.log(el);
        
        let dynamicRouter: RouteRecordRaw = {
          path: '/' + el.name,
          name: el.name,
          component: () => import("../views/Layout.vue"),
          children: []
        };
        el.children?.forEach((item, index) => {
          if (index === 0) {
            dynamicRouter.redirect = '/' + el.name + '/' + item.name;//重定向的路径
          }
          dynamicRouter.children?.push({
            path: item.name,
            name: item.name,
            component: () => import(`../views/${el.name}/${item.name}.vue` ),
            meta: {
              title: item.title,
              parentTitle: el.title,
              parentPath: '/' + el.name,
            }
          })
          // 假设某个分类有路由权限,同时具备子路由的权限
        })
        router.addRoute(dynamicRouter)//添加动态路由
        // console.log(dynamicRouter);

      })
      next(to.fullPath);
    } catch {
      Cookies.remove('token')
      next('/login')
    }

  } else if (!token && to.path !== "/login") {
    next("/login");
  } else {
    next();
  }
});

export default router
